package InterviewTest.q0205_addTwoNumbers;

import CommonClass.Common.ListNode;
public class Solution {
    /*
    与第二题相同 但是优化了计算流程 使while循环中不需要反复判断head是否为null
     */
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        // 先构建第一个节点head
        int startVal = l1 == null ? 0 : l1.val;
        startVal += l2 == null ? 0 : l2.val;
        ListNode head = new ListNode(startVal % 10);
        ListNode tail = head;
        int carry = startVal / 10;

        l1 = l1 == null ? null : l1.next;
        l2 = l2 == null ? null : l2.next;
        while (l1 != null || l2 != null) {
            int n1 = l1 == null ? 0 : l1.val;
            int n2 = l2 == null ? 0 : l2.val;
            int sum = n1 + n2 + carry;
            tail.next = new ListNode(sum % 10);
            tail = tail.next;
            carry = sum / 10;
            if (l1 != null) l1 = l1.next;
            if (l2 != null) l2 = l2.next;
        }
        if (carry > 0) tail.next = new ListNode(carry);

        return head;
    }
}
